package com.cnoc.base.zfqueue.impl;


import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cnoc.base.datatype.ZObjectUtils;
import com.cnoc.base.zfqueue.event.QueueInterface;
import com.cnoc.base.zfqueue.factory.QueueFQueueFactory;
import com.google.code.fqueue.FQueue;
@Component(value="QueueFQueueImpl")
public class QueueFQueueImpl implements QueueInterface {
    private static final Logger logger = Logger.getLogger(QueueFQueueImpl.class);  
    
    @Autowired
    QueueFQueueFactory queueFQueueFactory;
	public QueueFQueueImpl(){
		
	}
		@Override
	public Boolean put(String queueName, String key, Object value) throws Exception {
		try {
			Object[] objs = new Object[] { key, value };
//			QueueFQueueFactory queueFQueueFactory = (QueueFQueueFactory) ApplicationContextUtils.getBean("QueueFQueueFactory");
			FQueue fqueue = queueFQueueFactory.getFQueueInstance(queueName);
					
			fqueue.add(ZObjectUtils.toByteArray(objs));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	@Override
	public Boolean put(String queueName, Object value) throws Exception {
		try {
			FQueue fqueue = queueFQueueFactory.getFQueueInstance(queueName);
//			fqueue.add(ZObjectUtils.toByteArray(value));
			fqueue.add(ZObjectUtils.objectToByte(value));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public  Object pop(String queueName) throws Exception {
		FQueue fqueue = queueFQueueFactory.getFQueueInstance(queueName);
//		Object[] value = (Object[])ZObjectUtils.toObject(fqueue.poll());
		Object value = null ;
		if(this.count(queueName)>0){
			value = ZObjectUtils.byteToObject(fqueue.poll());
		}
		return value;
	}

	@Override
	public  long count(String queueName) throws Exception {
		FQueue fqueue = queueFQueueFactory.getFQueueInstance(queueName);
		return fqueue.size();
	}

}
